package com.tobey.logfetch.util;

import ch.ethz.ssh2.Connection;
import ch.ethz.ssh2.Session;
import ch.ethz.ssh2.StreamGobbler;
import com.tobey.logfetch.vo.ResultVo;
import org.apache.commons.lang3.StringUtils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

/**
 * 远程执行linux的shell script
 *
 * @author tangbing
 * @date 2019/3/6
 */
public class RemoteExecuteCommand {
    /**
     * 字符编码默认是utf-8
     */
    private static String DEFAULT_CHART = "UTF-8";
    private static Connection conn;
    private String ip;
    private int port;
    private String userName;
    private String userPwd;

    private RemoteExecuteCommand(String ip, int port, String userName, String userPwd) {
        this.ip = ip;
        this.port = port;
        this.userName = userName;
        this.userPwd = userPwd;
    }

    /**
     * 远程登录linux的主机
     *
     * @return 登录成功返回true，否则返回false
     */
    public Boolean login() {
        boolean flg = false;
        try {
            conn = new Connection(ip, port);
            conn.connect();//连接
            //认证
            flg = conn.authenticateWithPassword(userName, userPwd);
            if (flg) {
                System.out.println("认证成功！");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return flg;
    }

    /**
     * @param cmd 即将执行的命令
     * @return 命令执行完后返回的结果值
     * 远程执行shll脚本或者命令
     */
    public String execute(String cmd) {
        String result = "";
        try {
            if (login()) {
                //打开一个会话
                Session session = conn.openSession();
                //执行命令
                session.execCommand(cmd);
                result = processStdout(session.getStdout(), DEFAULT_CHART);
                //如果为得到标准输出为空，说明脚本执行出错了
                if (StringUtils.isBlank(result)) {
                    result = processStdout(session.getStderr(), DEFAULT_CHART);
                }
                conn.close();
                session.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result;
    }


    /**
     * @param cmd 即将执行的命令
     * @return 命令执行成功后返回的结果值，如果命令执行失败，返回空字符串，不是null
     * 远程执行shll脚本或者命令
     */
    public String executeSuccess(String cmd) {
        String result = "";
        try {
            if (login()) {
                //打开一个会话
                Session session = conn.openSession();
                //执行命令
                session.execCommand(cmd);
                result = processStdout(session.getStdout(), DEFAULT_CHART);
                conn.close();
                session.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 解析脚本执行返回的结果集
     *
     * @param in      输入流对象
     * @param charset 编码
     * @return 以纯文本的格式返回
     */
    public static String processStdout(InputStream in, String charset) {
        InputStream stdout = new StreamGobbler(in);
        StringBuffer buffer = new StringBuffer();
        try {
            BufferedReader br = new BufferedReader(new InputStreamReader(stdout, charset));
            String line = null;
            while ((line = br.readLine()) != null) {
                System.out.println(line);
                buffer.append(line + "\n");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return buffer.toString();
    }

    /**
     * sshCommand
     *
     * @param ip     ssh地址
     * @param pwd    ssh密码
     * @param no     新收费站号 4位
     * @param laneNo 车道号
     * @return ResultVo
     */
    public static ResultVo sshCommand(String ip, String pwd, String no, String laneNo) {
        ResultVo resultVo = new ResultVo();
        RemoteExecuteCommand rec = new RemoteExecuteCommand(ip, 22, "root", pwd);
        //执行命令
        try {
            if (rec.login()) {
                // 查看文件是否存在
                resultVo.setConfig(readConfigLogFile("/EMRC-ETC/CONFIG/Config.ini", conn, no, laneNo));
                /*resultVo.setAppFunction(fileExist("/EMRC-ETC/CONFIG/AppFunction.ini", conn, no, laneNo));
                resultVo.setCommunctionConfig(fileExist("/EMRC-ETC/CONFIG/CommunctionConfig.ini", conn));*/
                resultVo.setFaremtcDb(fileExist("/EMRC-ETC/CONFIG/FAREMTC.db", conn));
                resultVo.setFareetcDb(fileExist("/EMRC-ETC/CONFIG/FAREETC.db", conn));
                resultVo.setFarecpcDb(fileExist("/EMRC-ETC/CONFIG/FARECPC.db", conn));
                conn.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return resultVo;
    }

    public static boolean fileExist(String path, Connection conn) {
        if (conn != null) {
            Session ss = null;
            try {
                ss = conn.openSession();
                ss.execCommand("ls -l ".concat(path));
                InputStream is = new StreamGobbler(ss.getStdout());
                BufferedReader brs = new BufferedReader(new InputStreamReader(is));
                String line = "";
                while (true) {
                    String lineInfo = brs.readLine();
                    if (lineInfo != null) {
                        line = line + lineInfo;
                    } else {
                        break;
                    }
                }
                brs.close();
                if (line != null && line.length() > 0 && line.startsWith("-")) {
                    return true;
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                // 连接的Session和Connection对象都需要关闭
                if (ss != null) {
                    ss.close();
                }
            }
        }
        return false;
    }

    public static List<String> readConfigLogFile(String path, Connection conn, String no, String laneNo) {
        List<String> configList = new ArrayList<>();
        if (conn != null) {
            Session ss = null;
            try {
                ss = conn.openSession();
                ss.execCommand("tail -1000 ".concat(path));
                InputStream is = new StreamGobbler(ss.getStdout());
                BufferedReader brs = new BufferedReader(new InputStreamReader(is));
                while (true) {
                    String line = brs.readLine();
                    if (line == null) {
                        break;
                    } else {
                        if (line.contains("NetNo")) {
                            String twoNo = line.substring(line.indexOf("<") + 1, line.indexOf(">"));
                            if (!StringUtils.equals(no.substring(0, 2), twoNo)) {
                                configList.add("NetNo参数错误");
                            }
                        }
                        if (line.contains("PlazaNo")) {
                            String twoNo = line.substring(line.indexOf("<") + 1, line.indexOf(">"));
                            if (!StringUtils.equals(no.substring(0, 2), twoNo)) {
                                configList.add("PlazaNo参数错误");
                            }
                        }
                        if (line.contains("LaneNo")) {
                            String fileLaneNo = line.substring(line.indexOf("<") + 1, line.indexOf(">"));
                            if (!StringUtils.equals(fileLaneNo, laneNo)) {
                                configList.add("LaneNo参数错误");
                            }
                        }
                        if (line.contains("LaneType")) {
                            String laneType = line.substring(line.indexOf("<") + 1, line.indexOf(">"));
                            String firstLaneNo = laneNo.substring(0, 1);
                            if (StringUtils.equals(firstLaneNo, "X")) {
                                if (!StringUtils.equals(laneType, "1")) {
                                    configList.add("LaneType参数错误");
                                }
                            }
                        }
                        System.out.println(line);
                    }
                }
                brs.close();
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                // 连接的Session和Connection对象都需要关闭
                if (ss != null) {
                    ss.close();
                }
                if (conn != null) {
                    conn.close();
                }
            }
        }
        return configList;
    }

    public static void main(String[] args) {
        String line = "1314";
        String twoNo = line.substring(0, 2);
        System.out.println(twoNo);

    }


    public static void setCharset(String charset) {
        DEFAULT_CHART = charset;
    }

    public Connection getConn() {
        return conn;
    }

    public void setConn(Connection conn) {
        this.conn = conn;
    }

    public String getIp() {
        return ip;
    }

    public void setIp(String ip) {
        this.ip = ip;
    }

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public String getUserPwd() {
        return userPwd;
    }

    public void setUserPwd(String userPwd) {
        this.userPwd = userPwd;
    }

    public int getPort() {
        return port;
    }

    public void setPort(int port) {
        this.port = port;
    }
}
